﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Server.Controllers
{
    public class File2Controller : Controller
    {
        private string filePath = @"D:\Adobe_Dreamweaver_CS5-jfsky.rar";

        public ActionResult Index()
        {
            return View();
        }


        // GET: File2
        public void Download()
        {
            //前面可以做用户登录验证、用户权限验证等。

            string filename = Path.GetFileName(filePath);   //客户端保存的文件名  
            //string filePath = Server.MapPath("/App_Data/大数据.rar");//要被下载的文件路径 
            var range = Request.Headers["Range"];
            if (!string.IsNullOrWhiteSpace(range))//如果遵守协议，支持断点续传
            {
                var fileLength = new FileInfo(filePath).Length;//文件的总大小
                long begin;//文件的开始位置
                long end;//文件的结束位置
                long.TryParse(range.Split('=')[1].Split('-')[0], out begin);
                long.TryParse(range.Split('-')[1], out end);
                end = end - begin > 0 ? end : 65536>fileLength-1? fileLength-1: 65536;// 如果没有结束位置，默认给一个大小
                
                var buffer = new byte[end-begin+1];
                using (var fileStream = System.IO.File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    fileStream.Seek(begin, SeekOrigin.Begin);
                    fileStream.Read(buffer, 0, buffer.Length);
                }

                //表头 表明  下载文件的开始、结束位置 和文件总大小
                Response.AddHeader("Content-Range", "bytes " + begin + "-" + end + "/" + fileLength);
                Response.Headers.Add("Content-Length", buffer.Length.ToString());
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
                Response.OutputStream.Write(buffer, 0, buffer.Length);//发送 文件开始位置读取的大小
                Response.Flush();
                Response.End();
            }
            else
            {
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
                Response.TransmitFile(filePath);
            }
        }
    }
}